﻿using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI;
using System.Net.NetworkInformation;
using TeachlyQBank.DbServer;
using TeachlyQBank.Models;

namespace TeachlyQBank.Controllers
{
    public class KnowledgeController : Controller
    {
        private readonly KnowledgeServer _knowledgeServer;

        public KnowledgeController(KnowledgeServer knowledgeServer)
        { 
            _knowledgeServer = knowledgeServer;
        }

        // 功能:导航到添加一个知识点的视图
        // 参数:不需要传递任何参数
        // 返回:对应的视图
        public IActionResult AddKnowledge()
        {
            return View();
        }

        // 功能:返回展示所有知识点的视图,在这个视图也可以完成对知识点的修改和擅长
        // 参数:不需要传递任何参数
        // 返回:对应的视图
        public IActionResult ShowKnowledge(int page=1)
        {
            int PageSzie = 10;

            List<Knowledge> knowledgeList = new List<Knowledge>();

            knowledgeList = _knowledgeServer.GetKnowledgeList();

            return View(knowledgeList);
        }

      
        // 功能:添加一个知识点
        // 参数:传递一个Knowledge里面包含了创建知识点的名称和内容
        // 返回:重新返回添加知识点的视图
        public IActionResult AddKnowledgeSumbit(Knowledge knowledge)
        {
            // 对传递回来的数据进行检验
        

            HttpContext currentContext = this.HttpContext;
            if (_knowledgeServer.AddKnowledge(knowledge, currentContext) > 0)
            {
                //添加成功后的逻辑
                TempData["Message"] = "添加成功！";
            }
            else
            {
                //添加失败后的逻辑
                TempData["Message"] = "添加失败！";
            }
            return View("AddKnowledge");
        }

        // 功能:接受前台传递过来的ajax请求,删除一个知识点
        // 参数:接受一个Guid是知识点的id
        // 返回:删除成功返回Json的成功,返回失败
        [HttpPost]
        public IActionResult KnowledgeDelete(Guid id)
        {
            // 调用服务来删除知识点
            int count = _knowledgeServer.DeleteKnowledge(id);

            if ( count > 0 )
            {
                return Json(new { success = true });
            }
            else
            {
                return Json(new { success = false });
            }
        }

        [HttpPost]
        public IActionResult ReviseKnowledge(Knowledge knowledge)
        {
            if (knowledge == null )
            { 
                return Json(new { success = false});
            }

            int count = _knowledgeServer.ReviseKnowledge(knowledge);

            if (count == 1)
            {
                return Json(new { success = true });
            }
            else
            {
                return Json(new { success = false});
            }
        }
        
    }
}
